<template>
  <div class="container">
    <div class="filter-container machine-group">
      <!-- <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="createHandle">
        执行机组
      </el-button> -->
      <el-input v-model="dataForm.groupName" placeholder="请输入组名" size="medium" style="width: 200px; margin-right: 10px;" class="filter-item" @keyup.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-plus" size="medium" @click="createHandle">
        新增执行机组
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-download" size="medium" @click="downloadSlaveHandle">
        下载执行机端
      </el-button>
      <el-button class="filter-item" type="danger" icon="el-icon-delete" size="medium" @click="batchDelHandle">
        批量删除
      </el-button>
      <el-button class="filter-item export" type="success" icon="el-icon-download" size="medium" @click="exportExcelHandle">
        导出
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-refresh" size="medium" @click="refreshHandle">
        刷新
      </el-button>
    </div>
    <el-table
      border
      highlight-current-row
      :data="pageData"
      style="width: 100%"
      @selection-change="selectRowHandle"
      @sort-change="tableSortChange"
    >
      <el-table-column
        type="selection"
        align="center"
        width="55"
      />
      <el-table-column
        prop="id"
        label="ID"
        align="center"
        sortable
        min-width="90"
      />
      <el-table-column
        prop="group_name"
        align="center"
        :show-overflow-tooltip="true"
        label="组名"
        min-width="180"
      />
      <el-table-column
        prop="slave_count"
        sortable
        align="center"
        min-width="100"
        label="执行机"
      >
        <template slot-scope="{row}">
          <el-tag class="slave_count" @click="listSlaveTable(row)">{{ row.slave_count }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="create_time"
        sortable
        align="center"
        min-width="140"
        label="创建时间"
      />
      <el-table-column
        prop="creator_name"
        align="center"
        label="创建人"
      />
      <el-table-column
        prop="mark"
        align="center"
        min-width="180"
        :show-overflow-tooltip="true"
        label="备注"
      />
      <el-table-column label="操作" fixed="right" header-align="center" align="center" min-width="120">
        <template v-if="scope.row.id != 1" slot-scope="scope">
          <el-button type="text" size="small" @click="editHandle(scope.row,0)">编辑</el-button>
          <el-button type="text" size="small" @click="editHandle(scope.row,1)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        :current-page="pageIndex"
        :page-sizes="[10, 15, 30, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 执行组编辑弹出框 -->
    <MachineGroupDialog
      v-if="showDialog"
      :group-table-item="groupTableItem"
      @closeDialog="closeDialog"
    />

    <Slave
      v-if="slaveShowDialog"
      :machine-list-item="machineListItem"
      @closeSlaveDialog="closeSlaveDialog"
    />
  </div>
</template>

<script>
import { delMachineGroup, listMachineGroup, downloadSlaveZip } from '@/api/machine-group'
import { exportExcel } from '@/utils/exportExcelUtils'
import MachineGroupDialog from '@/views/machineGroup/components/MachineGroupDialog'
import Slave from '@/views/machineGroup/components/slave'
import { batchHandle } from '@/utils/commonUtil'

export default {
  name: 'MachineGroup',
  components: {
    MachineGroupDialog,
    Slave
  },
  filters: {
    typeFilter(type) {
      return type
    }
  },
  data() {
    return {
      tableData: [],
      selectIds: [],
      filterTableData: [],
      pageSize: 10, // 每页大小默认值
      pageIndex: 1, // 默认第一页
      groupTableItem: {
        id: undefined,
        group_name: '',
        mark: '',
        status: ''
      },
      showDialog: false,
      MachineGroupTitle: '新增执行组',
      slaveShowDialog: false,
      // 执行列表弹出框
      machineListItem: {
        visible: false,
        status: '',
        group_id: '',
        group_name: '',
        mode: 0 // 按钮控制
      },
      choosePage: {
        visible: false,
        value: undefined,
        options: []
      },
      drawer: {
        visible: false,
        direction: 'rtl'
      },
      dataForm: {
        groupName: ''
      }
    }
  },
  computed: {
    locationBy() {
      return this.$store.state.user.dictConfig.locationBy
    },
    elementType() {
      return this.$store.state.user.dictConfig.elementType
    },
    // 总数
    total() {
      return this.tableData.length
    },
    // 当前分页数据
    pageData() {
      return this.tableData.slice((this.pageIndex - 1) * this.pageSize, this.pageIndex * this.pageSize)
    }

  },
  watch: {
    tableData() {
      this.pageIndex = 1
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    // 条件查询
    handleFilter() {
      const data = []
      Object.assign(data, this.tableData)
      this.tableData = this.selfHandleFilter(data)
    },
    // 详细的过滤操作，需要覆写此方法
    selfHandleFilter(data) {
      if (this.dataForm.groupName !== '') {
        data = data.filter(item => item.group_name.indexOf(this.dataForm.groupName) !== -1)
      }
      if (this.dataForm.groupName === '') {
        this.getData()
      }
      return data
    },
    // 表格排序
    tableSortChange({ column, prop, order }) {
      this.tableData.sort(function(a, b) {
        return order === 'ascending' ? a[prop] - b[prop] : b[prop] - a[prop]
      })
    },
    selectRowHandle(selection) {
      this.selectIds = []
      const self = this
      selection.forEach(function(row) {
        self.selectIds.push(row.id)
      })
    },
    createHandle() {
      this.groupTableItem = {
        id: undefined,
        group_name: '',
        mark: '',
        status: 'create'
      }
      this.showDialog = true
    },
    editHandle(row, state) {
      // 编辑
      if (state === 0) {
        this.groupTableItem = {
          id: row.id,
          group_name: row.group_name,
          mark: row.mark,
          status: 'update'
        }
        this.showDialog = true
      } else { // 删除
        this.$confirm('是否删除页面元素 【' + row.group_name + '】 ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delMachineGroup({ id: row.id }).then(response => {
            this.getData()
            this.$message.success('删除成功')
          })
        }).catch(() => {
        })
      }
    },
    // 关闭组名edit操作
    closeDialog(flag) {
      if (flag) {
        // 重新刷新表格内容
        this.getData()
      }
      this.showDialog = false
    },
    closeSlaveDialog(flag) {
      if (flag) {
        // 重新刷新表格内容
        this.getData()
      }
      this.slaveShowDialog = false
    },
    // handleFilter() {
    //   const data = []
    //   Object.assign(data, this.tableData)
    //   this.filterTableData = data
    // },
    getData() {
      const params = {}
      listMachineGroup(params).then(response => {
        this.tableData = response.data
      })
    },
    refreshHandle() {
      this.getData()
    },
    // 执行机相关
    listSlaveTable(row) {
      console.log(row)
      this.machineListItem = {
        visible: true,
        status: 'show',
        group_id: row.id,
        group_name: row.group_name
      }
      this.slaveShowDialog = true
    },
    updateSlaveHandle(row) {
      this.slave.visible = true
      this.slave.status = 'show'
      this.slave.temp.id = row.id
      this.slave.temp.slave_name = row.slave_name
      this.slave.temp.mark = row.slave_name
      this.slave.temp.parallel_max = row.parallel_max
    },
    downloadSlaveHandle() {
      downloadSlaveZip()
    },
    // 前端分页： 当前页码改变
    handleCurrentChange(val) {
      this.pageIndex = val
    },
    // 前端分页：分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
    },
    // 批量删除
    batchDelHandle() {
      if (this.selectIds.length === 0) {
        this.$message.warning('请先选择至少一行数据!')
        return
      }
      const self = this
      batchHandle({
        vm: self,
        opName: '删除',
        data: self.selectIds,
        opHandle(val, resolve, reject) {
          delMachineGroup({ id: val }).then(() => {
            resolve()
          }).catch(() => {
            reject()
          })
        },
        finishCallback(successCount, failCount) {
          self.getData()
        }
      })
      // const failCount = 0
      // const self = this
      // this.$confirm('是否批量删除选择的共 ' + this.selectIds.length + ' 条数据？', '警告', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   const intervalId = setInterval(function() {
      //     self.getData()
      //     clearInterval(intervalId)
      //     if (failCount === 0) {
      //       self.$notify({
      //         title: '通知',
      //         message: '删除成功',
      //         type: 'success',
      //         duration: 2000
      //       })
      //     } else {
      //       self.$notify({
      //         title: '通知',
      //         message: '共' + failCount + '条数据删除失败',
      //         type: 'error',
      //         duration: 2000
      //       })
      //     }
      //   }, 300)
      // }).catch()
    },
    // 导出
    exportExcelHandle() {
      const tHeader = ['ID', '组名', '执行机', '创建时间', '创建人', '备注']// 上面设置Excel的表格第一行的标题
      const filterVal = ['id', 'group_name', 'slave_count', 'create_time', 'creator_name', 'mark'] // 上面的index、nickName、name是tableData里对象的属性
      const list = this.tableData // 把data里的tableData存到list
      const data = this.formatJson(filterVal, list)
      const excelName = '执行组'
      exportExcel(tHeader, data, excelName)
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    }
  }
}
</script>

<style scoped>
  .container {
    padding-left: 25px;
    padding-right: 25px;
  }
  .machine-group {
    margin: 20px 0px 0px 0px;
  }

  .edit-form {
    width: 80%;
  }

  .input-countent {
    width: 97%;
  }

  .remark > [for='mark'] {
    padding-left: 10px;
  }

  .slave-main {
    margin: 0;
    padding: 0;
  }
  .export {
    float: right;
  }

  .slave_count{
    cursor:pointer;
  }
</style>
